package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.entity.Result;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.service.seckill.SeckillOrderService;
import com.qingcheng.util.SeckillStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: LDeng
 * @Date: 2020-07-15 16:55
 */

@RestController
@RequestMapping(value = "/seckill/order")
public class SeckillOrderController {

    //用户下单操作
    //@param 商品所在的时间区间
    //@param id 商品id

    @Reference
    private SeckillOrderService seckillOrderService;


    //根据用户名查询用户用户抢单状态  URL: /sekill/order/query
    @RequestMapping(value = "/query")
    public Result queryStatus() {
        //获取用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        if (username.equals("anonymousUser")) {
            return new Result(403, "未登录， 请先登录");
        }
        //调用service查询
        try {
            SeckillStatus seckillStatus = seckillOrderService.queryStatus(username);
            if (seckillStatus != null) {
                Result result = new Result(seckillStatus.getStatus(), "抢单中！");
                System.out.println("Controller中的OrderId============>"+seckillStatus.getOrderId());
                    result.setOther(seckillStatus);
                    return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //0 抢单失败
            return new Result(0,e.getMessage());
        }

        return new Result(404, "无相关信息");
    }


    @RequestMapping(value = "/add")
    public Result add(Long id, String time) {
        //获取用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        //如果用户没登录则提醒用户登录
        if (username.equals("anonymousUser")) {
            return new Result(403, "未登录， 请先登录");
        }
        //调用service 下单操作
        try {
            Boolean add = seckillOrderService.add(id, time, username);

            if (add) {
                return new Result(0, "抢单成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //将错误信息返回出去
            return new Result(2,e.getMessage());
        }

        return new Result(1, "抢单失败");
    }

}
